package biz.alla.market.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import biz.alla.market.domain.User;
import biz.alla.market.service.MarketService;
import biz.alla.market.web.WebConstants;

@Controller
public class UserController {
    private MarketService marketService;

    protected static final String MODEL_ATTRIBUTE_USER = "user";
    protected static final String REDIRECT_PREFIX = "redirect:";
    protected static final String LOGIN_VIEW = "login";
    protected static final String REGISTRATION_VIEW = "registration";
    protected static final String VIEW_HOME = "/home.do";
    public static final String VIEW_LOGIN = "login.do";

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegistration(ModelMap model) {
	model.put(MODEL_ATTRIBUTE_USER, new User());

	return REGISTRATION_VIEW;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showLogin(ModelMap model) {
	model.put(MODEL_ATTRIBUTE_USER, new User());

	return LOGIN_VIEW;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String submitLogin(HttpServletRequest request, User user) {
	user = marketService.isValidUser(user.getUsername(), user.getPassword());

	if (user != null) {
	    HttpSession session = request.getSession();
	    session.setAttribute(WebConstants.SESSION_ATTR_USER, user);
	    return REDIRECT_PREFIX + VIEW_HOME;
	}

	return LOGIN_VIEW;
    }

    public void setMarketService(MarketService marketService) {
	this.marketService = marketService;
    }
}
